const methods = require("methods");
// 每个layer都有route属性，没有的是中间件
const Layer = require("./layer");
function Route() {
  this.stack = [];
  this.methods = [];
}
methods.forEach((method) => {
  Route.prototype[method] = function (handlers) {
    handlers.forEach((handle) => {
      let layer = new Layer("/", handle);
      layer.method = method;
      this.methods[method] = true;
      this.stack.push(layer);
    });
  };
});
Route.prototype.dispatch = function (req, res, out) {
  let idx = 0;
  let method = req.method.toLowerCase();
  const dispatch = (err) => {
    if (err) return out(err);
    if (idx === this.stack.length) return out();
    let layer = this.stack[idx++];
    if (method === layer.method) {
      layer.handle_request(req, res, dispatch);
    } else {
      dispatch();
    }
  };
  dispatch();
};

module.exports = Route;
